<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="queryParams.keywords" placeholder="菜单名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <!-- <el-button v-hasPerm="['sys:menu:add']" type="success" icon="plus" @click="handleOpenDialog('0')">
          新增
        </el-button> -->
        <!-- <el-button type="success" icon="plus" @click="handleForm_action('add', 0)">
          新增
        </el-button> -->
      </div>

      <el-table v-loading="loading" :data="menuTableData" highlight-current-row row-key="id" :tree-props="{
        children: 'children',
        hasChildren: 'hasChildren',
      }" @row-click="handleRowClick">
        <el-table-column label="菜单名称" min-width="200">
          <template #default="scope">
            <template v-if="scope.row.icon && scope.row.icon.startsWith('el-icon')">
              <el-icon style="vertical-align: -0.15em">
                <component :is="scope.row.icon.replace('el-icon-', '')" />
              </el-icon>
            </template>
            <template v-else-if="scope.row.icon">
              <div :class="`i-svg:${scope.row.icon}`" />
            </template>
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column label="类型" align="center" width="80">
          <template #default="scope">
            <el-tag v-for="type in menuType" v-show="scope.row.type === type.value" :type="type.type">{{
              type.label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="路由名称" align="left" width="150" prop="routeName" />
        <el-table-column label="路由路径" align="left" width="150" prop="routePath" />
        <el-table-column label="组件路径" align="left" width="250" prop="component" />
        <el-table-column label="权限标识" align="center" width="200" prop="perm" />
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.visible === 1" type="success">显示</el-tag>
            <el-tag v-else type="info">隐藏</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" width="80" prop="sort" />
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <!-- <el-button v-if="scope.row.type == MenuTypeEnum.CATALOG || scope.row.type == MenuTypeEnum.MENU"
              v-hasPerm="['sys:menu:add']" type="primary" link size="small" icon="plus"
              @click.stop="handleOpenDialog(scope.row.id)">
              新增
            </el-button>

            <el-button v-hasPerm="['sys:menu:edit']" type="primary" link size="small" icon="edit"
              @click.stop="handleOpenDialog(undefined, scope.row.id)">
              编辑
            </el-button>
            <el-button v-hasPerm="['sys:menu:delete']" type="danger" link size="small" icon="delete"
              @click.stop="handleDelete(scope.row.id)">
              删除
            </el-button> -->
            <el-button v-if="scope.row.type == menuType[0].value || scope.row.type == menuType[1].value" type="primary"
              link size="small" icon="plus" @click.stop="handleForm_action('add', scope.row.id)">
              新增
            </el-button>
            <el-button type="primary" link size="small" icon="edit" @click.stop="handleForm_action('edit', scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" icon="delete" @click.stop="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <custom-form ref="custom_form" :menuSelectTree="menuSelectTree" :menuType="menuType" @subemit="subemit" />
  </div>
</template>

<script setup>
defineOptions({
  name: "SysMenu",
  inheritAttrs: false,
});

// 菜单类型
const menuType = [
  { label: '目录', value: 1, type: 'warning' },
  { label: '菜单', value: 2, type: 'success' },
  { label: '按钮', value: 3, type: 'danger' },
  { label: '外链', value: 4, type: 'info' },
]

import CustomForm from './customForm.vue';
import MenuAPI from "@/api/system/menu.api";
import { MenuTypeEnum } from "@/enums/system/menu.enum";

// 表单实例
const custom_form = ref(null);

//表单提交
function subemit() {
  handleQuery()
  // s_table.value.refresh();
};

//操作表单
function handleForm_action(ty, data) {
  custom_form.value.showForm(ty, data);
};

const queryFormRef = ref();
const menuFormRef = ref();

const loading = ref(false);
const dialog = reactive({
  title: "新增菜单",
  visible: false,
});

// 查询参数
const queryParams = reactive({
  keywords: ''
});
// 菜单表格数据

// 初始菜单表单数据
const initialMenuFormData = ref({
  id: undefined,
  parentId: "0",
  visible: 1,
  sort: 1,
  type: MenuTypeEnum.MENU, // 默认菜单
  alwaysShow: 0,
  keepAlive: 1,
  params: [],
});
// 菜单表单数据
const formData = ref({ ...initialMenuFormData.value });
// 表单验证规则


// 选择表格的行菜单ID
const selectedMenuId = ref();


const menuTableData = ref([]); // 表格数据
const menuSelectTree = ref([]); // 菜单数据（表单父级选择）
// 查询菜单
function handleQuery() {
  loading.value = true;
  MenuAPI.getList(queryParams)
    .then(res => {
      menuTableData.value = res;

      //用于表单选择父级菜单
      menuSelectTree.value = [{ label: '顶级菜单', value: 0, children: selectTreeFilter(res) }]
    })
    .finally(() => {
      loading.value = false;
    });
}

//去除菜单里的按钮(递归)
function selectTreeFilter(list) {
  return list.filter(v => v.type !== 3).map(j => {
    return {
      label: j.name,
      value: j.id,
      children: selectTreeFilter(j.children)
    }
  })
}


// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 行点击事件
function handleRowClick(row) {
  selectedMenuId.value = row.id;
}

/**
 * 提交表单
 */
function handleSubmit() {
  menuFormRef.value.validate((isValid) => {
    if (isValid) {
      const menuId = formData.value.id;
      if (menuId) {
        //修改时父级菜单不能为当前菜单
        if (formData.value.parentId == menuId) {
          ElMessage.error("父级菜单不能为当前菜单");
          return;
        }
        MenuAPI.update(menuId, formData.value).then(() => {
          ElMessage.success("修改成功");
          handleCloseDialog();
          handleQuery();
        });
      } else {
        MenuAPI.create(formData.value).then(() => {
          ElMessage.success("新增成功");
          handleCloseDialog();
          handleQuery();
        });
      }
    }
  });
}

// 删除菜单
function handleDelete(id) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    MenuAPI.delete(id).then(() => {
      ElMessage.success("删除成功");
      handleQuery();
    })
      .finally(() => {
        loading.value = false;
      });
  }, () => {
    ElMessage.info("已取消删除");
  });
}

function resetForm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();
  formData.value = {
    id: undefined,
    parentId: "0",
    visible: 1,
    sort: 1,
    type: MenuTypeEnum.MENU, // 默认菜单
    alwaysShow: 0,
    keepAlive: 1,
    params: [],
  };
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>
